package com.act.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CommonUtils {
	
	private static final Log log = LogFactory.getLog(CommonUtils.class);
	
	/**
	 * @param seq 序列名称
	 * @param num 集合大小
	 * @return
	 */
	public synchronized static Map<String,Long> getSeq(String tableName,long num){
		String sequenceName = tableName.toUpperCase() + "_SE";
		Map<String,Long>  map = new HashMap<String,Long>();
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			getSequenceName(sequenceName,conn);
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select "+sequenceName+".nextval id from (select 1 from all_objects where rownum <= "+num+")");
			List<Long> list = new ArrayList<Long>();
			while (rs.next()) {
				list.add(rs.getLong(1));
			}
			if(list != null && list.size() > 0){
				map.put("minSeq",list.get(0));
				map.put("maxSeq",list.get(list.size()-1));
			}else{
				map.put("minSeq",-1L);
				map.put("maxSeq",-1L);
			}
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(rs, stmt, conn);
		}
		return map;
	}
	
	public static String getSequenceName(String sequenceName,Connection conn) {
        String sql1 = "SELECT SEQUENCE_NAME FROM user_sequences WHERE SEQUENCE_NAME='" + sequenceName + "'";
        PreparedStatement selectStatement = null;
        PreparedStatement insertStatement = null;
        ResultSet rs = null;
        try {
            selectStatement = conn.prepareStatement(sql1);
            rs = selectStatement.executeQuery();
            if (!rs.next()) {
                String sql2 = "CREATE SEQUENCE " + sequenceName + " start with 1 increment by 1";
                insertStatement = conn.prepareStatement(sql2);
                insertStatement.execute();
            }
        } catch (SQLException e) {
        	if(log.isErrorEnabled()){
        		log.error(e.getMessage(),e);
        	}
            return null;
        }finally{
        	JdbcUtil.close(insertStatement);
        	JdbcUtil.close(selectStatement);
        	JdbcUtil.close(rs);
        }
        return sequenceName;
    }
	
	/**
	 * 创建表序列，若序列不存在
	 * @param tableName
	 */
	public static void createSeqIfNotExists(String tableName){
		Connection conn = null;
		try{
			String sequenceName = tableName.toUpperCase() + "_SE";
			conn = JdbcUtil.getConnection();
			getSequenceName(sequenceName,conn);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(conn);
		}
	}
	
	public static String valueOf(Object object){
        String str = StringUtils.trim(String.valueOf(object));
        boolean check = StringUtils.isBlank(str) || StringUtils.equals(str, "null") || StringUtils.equals(str, "undefined");
        return check ? "" : str;
	}
	
	
	public static String getDomainSuffix(String domain){
		Pattern pattern = Pattern.compile("(\\d{1,3}\\.){3}(\\d{1,3})");
		String result = "";
		try{
			String topDomain = URLUtil.getDomainName("http://" + domain);
			if(StringUtils.isNotBlank(topDomain)){
				if(pattern.matcher(topDomain).matches()){//判断是否为IP
					result =  topDomain;
				}else{
					result = topDomain.substring(topDomain.indexOf(".") + 1,topDomain.length());
				}
			}else{
				//表示域名不符合规则
				if(domain.indexOf(".") > 0){
					result = domain.substring(domain.indexOf(".") + 1,domain.length());
				}else{
					result = domain;
				}
			}
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}
		return result;
	}
	
	public static boolean execSql(Connection conn,String sql){
    	boolean flag = true;
    	PreparedStatement ps = null;
    	try{
    		conn.setAutoCommit(false);
    		ps = conn.prepareStatement(sql);
          	ps.executeQuery();
            conn.commit();
          	flag = true;
          }
          catch(SQLException e){
         	 flag = false;
         	 log.error("jdbc batch commit sql:"+sql+" error" , e);
              try {
                  conn.rollback();
              } catch (SQLException e1) {
                  log.error("jdbc rollback error" , e1);
              }
          }finally{
        	  JdbcUtil.close(ps);
          }
    	return flag ;
    }
	
	public static String getExecDate(String dayStr) {
		if (StringUtils.isBlank(dayStr)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			dayStr = sdf.format(new Date());
		}
		return dayStr;
	}
	
	/**
	 * 判断是否为数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		try {
			Long.parseLong(str);
			return true;
		} catch (Exception ex) {
			return false;
		}
	}
}
